package org.xg.study.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName CheckCodeServlet
 * @date 2021/9/24 10:10
 **/
@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 120;
        int height = 30;
        //在内存中生成图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //先获取画笔对象
        Graphics2D g = image.createGraphics();
        //设置灰色
        g.setColor(Color.GRAY);
        //画填充的矩形
        g.fillRect(0, 0, width, height);
        //设置颜色
        g.setColor(Color.BLUE);
        //画边框
        g.drawRect(0, 0, width - 1, height - 1);
        //准备数据，随机获取4个字符
        String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        //设置颜色
        g.setColor(Color.YELLOW);
        //设置字体
        g.setFont(new Font("隶书", Font.BOLD, 20));
        String code = "";
        //构造存储字符的数组
        char[] c = {};
        //构造存储字符串的集合
        List<String> list = new ArrayList<String>();
        Random random = new Random();
        int x = 20;
        int y = 20;
        for (int i = 0; i < 4; i++) {
            int jiaodu = random.nextInt(60) - 30;
            double hudu = jiaodu * Math.PI / 180;
            g.rotate(hudu, x, y);
            int index = random.nextInt(words.length());
            char ch = words.charAt(index);
            char[] chc = {ch};
            String str = new String(chc);
            list.add(str);
            g.drawString("" + ch, x, y);
            g.rotate(-hudu, x, y);
            x += 20;
        }
        for (int i = 0; i < list.size(); i++) {
            code += list.get(i);
        }
        getServletContext().setAttribute("code", code);
        g.setColor(Color.GREEN);
        int x1, x2, y1, y2;
        //画干扰线
        for (int i = 0; i < 4; i++) {
            x1 = random.nextInt(width);
            x2 = random.nextInt(height);
            y1 = random.nextInt(width);
            y2 = random.nextInt(height);
            g.drawLine(x1, x2, y1, y2);
        }
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
